#!/usr/bin/env python
#  This file is part of OpenLightingDesigner.
# 
#  OpenLightingDesigner is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  OpenLightingDesigner is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with OpenLightingDesigner.  If not, see <http://www.gnu.org/licenses/>.
#
# main.py
# Copyright (c) 2010 - 2011 Matthew Reid

import sys
import time
import threading
import signal
import argparse

if type(sys.argv[0]) == unicode:
    sys.argv[0] = str(sys.argv[0])

from Bases.BaseObject import GLOBAL_CONFIG, garbage_collector

GLOBAL_CONFIG['app_name'] = 'openlightingdesigner'
GLOBAL_CONFIG['app_id'] = 'openlightingdesigner.app'

parser = argparse.ArgumentParser(prog=GLOBAL_CONFIG['app_name'])
parser.add_argument('-ui', choices=['gtk', 'kivy', 'text'], default='gtk', dest='ui')
parser.add_argument('--no-gi', default=False, action='store_true', dest='no_gi')
parser.add_argument('-f', dest='filename')
parser.add_argument('-d', default=False, action='store_true', dest='daemon')
parser.add_argument('--debug-osc', default=False, action='store_true', dest='debug_osc')
args = parser.parse_args()
o = vars(args)

uimode = o.get('ui')
if o['ui'] == 'text':
    o['daemon'] = True
elif o['daemon']:
    o['ui'] = 'text'
GLOBAL_CONFIG['ui_mode'] = o['ui']
GLOBAL_CONFIG['arg_parse_dict'] = o

from comm.CommDispatcher import CommDispatcher
from MainController import MainController
from ui.touchosc.touchosc_main import TouchOSC
#from ui.mrmr.mrmr_server import mrmrController
from ui.iOSCControl.iOSCController import iOSCController
import gc
#gc.set_threshold(500, 2, 1)
#gc.set_debug(gc.DEBUG_STATS)


def build_gtk():
    from ui.gtk.bases.ui_modules import gtk, gobject, gdk, glib
    class ExitObj(object):
        def on_exit(self, **kwargs):
            gtksimple.gCBThread.stop()
            #gtk.main_quit()
            garbage_collector.stop()
            print 'exit complete'
    #import gtk, gobject
    #glib.thread_init(0)
    #gdk.threads_init()
    #gtk.gdk.threads_enter()
    
    exitobj = ExitObj()
    from ui.gtk.gtkBaseUI import Application
    #from ui.gtk.mainwindow import MainWindow
    
    app = Application()
    GLOBAL_CONFIG['USE_BASEOBJECT_GARBAGE_COLLECTOR'] = True
    from ui.gtk.bases import gtksimple
    comm = CommDispatcher()
    mc = MainController(comm=comm)
    app.bind(exit=mc.on_app_exit)
    app.mainwindow_kwargs['MainController'] = mc
    globals()['exitobj'] = exitobj
    globals()['mc'] = mc
    mc.bind(app_exit_complete=exitobj.on_exit)
    iosc = iOSCController(MainController=mc)
    app.run()
    
    #w = MainWindow(DeviceSystem=mc.DeviceSystem, MainController=mc, comm=comm)
    #w.window.connect('destroy', mc.on_app_exit)
    #gtk.main()
    #gtk.gdk.threads_leave()
    print 'post gtkmain'
    sys.exit(0)
    
def build_qt():
    pass
    
def build_kivy():
    class ExitObj(object):
        def on_exit(self, **kwargs):
            sys.exit(0)
    exitobj = ExitObj()
    comm = CommDispatcher()
    mc = MainController(comm=comm)
    globals()['exitobj'] = exitobj
    globals()['mc'] = mc
    mc.bind(app_exit_complete=exitobj.on_exit)
    from ui.kivy.mainwindow import MainWindow
    w = MainWindow(MainController=mc)
    

def build_daemon():
    from daemon import Daemon
    comm = CommDispatcher()
    mc = MainController(comm=comm)
    iosc = iOSCController(MainController=mc)
    #tosc = TouchOSC(MainController=mc)
    d = Daemon(MainController=mc)
    garbage_collector.stop()
    
def build_osc_ola_host():
    from comm.dmx.OSCtoOLA import OSCtoOLAHost
    osc_ola = OSCtoOLAHost()

def on_window_destroyed(*args):
    pass

if __name__ == '__main__':
    if o['ui'] == 'text':
        build_daemon()
    #elif 'osc_ola' in sys.argv:
    #    build_osc_ola_host()
    elif o['ui'] == 'kivy':
        build_kivy()
    elif o['ui'] == 'gtk':
        build_gtk()
    
